//
//  KABHpEditSignVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/3/4.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABHpEditSignVC.h"
#import "KABModel.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "MBProgressHUD+XDPrompt.h"
#import "XDAFNetworking.h"

@interface KABHpEditSignVC () <UITextViewDelegate>

@property (weak, nonatomic) IBOutlet UITextView *summaryTextView;

@end

@implementation KABHpEditSignVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //显示键盘
    [self.summaryTextView becomeFirstResponder];
}


- (void)initNavigationBar {
    //导航栏title
    self.navigationItem.title = @"修改签名";
    
    //导航栏rightBarButtonItem保存按钮
    UIBarButtonItem * saveBBI = [[UIBarButtonItem alloc] initWithTitle:@"更新"
                                                                 style:UIBarButtonItemStylePlain
                                                                target:self
                                                                action:@selector(saveBtnTapped:)];
    //    saveBBI.tintColor = [self getUIColorFromHex:kCommonBlueColor andAlpha:1.0];
    self.navigationItem.rightBarButtonItem = saveBBI;
}

- (void)initSubViews {
    //禁止scrollview自动布局
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.summaryTextView.text = [KABModel sharedInstance].userInfo.sign;
//    self.summaryTextView.tintColor = WESTARS_COLOR_CURSOR_COLOR(1.0);
    self.summaryTextView.delegate = self;
//    self.summaryTextView.layoutManager.allowsNonContiguousLayout = NO;
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    NSString *toBeString = textView.text;
    //获取高亮部分
    UITextRange *selectedRange = [textView markedTextRange];
    UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position || !selectedRange) {
        if (toBeString.length > KABGlobalUserSignMaxLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:KABGlobalUserSignMaxLength];
            if (rangeIndex.length == 1) {
                textView.text = [toBeString substringToIndex:KABGlobalUserSignMaxLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, KABGlobalUserSignMaxLength)];
                textView.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

#pragma mark - event response
- (void)saveBtnTapped:(UIBarButtonItem *)btnItem {
    //保存数据
    if ([self.summaryTextView.text isEqualToString:[KABModel sharedInstance].userInfo.sign]) {
        [self goBackToParent];
        return;
    }
    
    // 校验输入参数
    if (!self.summaryTextView.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入个性签名"];
        return;
    }
    
    [self requestEditUserInfo];
}

#pragma mark - private methods
- (void)goBackToParent {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - network request
- (void)requestEditUserInfo {
    // 发布Cos需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"sign" : self.summaryTextView.text};
    
    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiModifyMyInfo] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"修改个人信息成功：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] updateNickName:nil
                                                  sex:-1
                                             province:nil
                                                 city:nil
                                                 sign:self.summaryTextView.text];
            [self goBackToParent];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"修改个人信息失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters

////点击其它地方隐藏键盘
//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//    [self.view endEditing:YES];
//}
//
////退出键盘时收回键盘
//- (void)textFieldDidEndOnExit:(UITextField *)textField {
//    [textField resignFirstResponder];
//}

#define kMaxNameLength  (10)
//- (void)textFieldDidChange:(UITextField *)textField {
//    if (textField == self.nameTextField) {
//        NSString *toBeString = textField.text;
//        //        NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式(有警告，改为下面一行)
//        NSString *lang = [textField.textInputMode primaryLanguage]; // 键盘输入模式
//        if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
//            UITextRange *selectedRange = [textField markedTextRange];
//            //获取高亮部分
//            UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
//            // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
//            if (!position) {
//                if (toBeString.length > kMaxNameLength) {
//                    textField.text = [toBeString substringToIndex:kMaxNameLength];
//                }
//            }
//            // 有高亮选择的字符串，则暂不对文字进行统计和限制
//            else{
//
//            }
//        }
//        // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
//        else{
//            if (toBeString.length > kMaxNameLength) {
//                textField.text = [toBeString substringToIndex:kMaxNameLength];
//            }
//        }
//    }
//}

@end
